<?php

namespace JsonLowCode\Form;

use JsonLowCode\Form\Enums\RuleEnum;
use JsonLowCode\Support\Fluent;

class Rule extends Fluent
{
    public function __construct($attributes = [])
    {
        parent::__construct($attributes);
        $this->trigger("blur");
    }

    /**
     * 设置 type
     * @param RuleEnum $type
     * @return $this
     */
    public function type(RuleEnum $type): static
    {
        $this->attributes['type'] = $type;
        return $this;
    }

    /**
     * 设置 required
     * @param bool|string $message
     * @return $this
     */
    public function required(bool|string $message = true): static
    {
        if (is_string($message)){
            $this->attributes['required'] = (bool)$message;
            $message&&$this->message($message);
        }else{
            $this->attributes['required'] = $message;
        }
        return $this;
    }

    /**
     * 设置 message
     * @param string $message
     * @return $this
     */
    public function message(string $message): static
    {
        $this->attributes['message'] = $message;
        return $this;
    }

    /**
     * 设置 正则
     * @param string $pattern
     * @return $this
     */
    public function pattern(string $pattern): static
    {
        $pattern = trim($pattern,"/");
        $this->attributes['pattern'] = JSExpression("new RegExp('{$pattern}')");
        return $this;
    }


    /**
     * 设置 trigger
     * @param string|array $trigger blur|input|focus|Array<blur|input|focus>
     * @return $this
     */
    public function trigger(string|array $trigger): static
    {
        $this->attributes['trigger'] = $trigger;
        return $this;
    }

    /**
     * 设置 renderMessage
     * @param mixed $renderMessage () => VNodeChild
     * @return $this
     */
    public function renderMessage(mixed $renderMessage): static
    {
        $this->attributes['renderMessage'] = $renderMessage;
        return $this;
    }

    /**
     * 设置 validator 函数
     * @param mixed $validator (rule: FormItemRule, value: any) => boolean | Error
     * @return $this
     */
    public function validator(string $validator): static
    {
        $this->attributes['validator'] = JSFunction($validator);
        return $this;
    }

    /**
     * 设置 asyncValidator 函数
     * @param mixed $asyncValidator (rule: FormItemRule, value: any, callback: (error?: Error) => void) => void
     * @return $this
     */
    public function asyncValidator(mixed $asyncValidator): static
    {
        $this->attributes['asyncValidator'] = $asyncValidator;
        return $this;
    }
}
